<template>
<!-- 权限点 -->
  <div>
    <!-- this is Permission -->
    <el-card>
      <div style="text-align: right; margin-bottom: 20px">
        <!-- 一级添加 -->
          <el-button type="primary" size="small" @click="add({ type: 1, pid: '' })">添加权限</el-button>
        </div>
      <!-- 
      1.当 row 中包含 children 字段时，被视为树形数据。
      渲染树形数据时，必须要指定 row-key -->
      <el-table 
      :data="list"
      row-key="id"
      border>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="标识" prop="code"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="操作">
          <template #default='{row}'>
            <!-- 二级add -->
            <el-button type="text" @click="add({ type: 2, pid: row.id })">添加</el-button>
            <el-button type="text" @click="edit(row.id)">编辑</el-button>
            <el-button type="text" @click="deletePermission(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--新增弹框 -->
    <add-permission
    ref="dialogForm" 
    :show-dialog="dialogVisible" 
    @close-dialog="closeDialog" 
    @up-date="fetchPermissionList"
    :add-type="addType"
    :add-pid="addPid">
    </add-permission>
  </div> 
</template>

<script>
/* 
新增的权限分为两类
1.点击上面的添加权限，添加时一级路由的访问权限也就是菜单的权限（type=1,pid="")
2.点击下面的添加权限点，添加的是路由对应组件里面按钮的操作权限(type=2,pid为当前需要添加的项id)
*/
import {getPermissionList, delPermission} from '@/api/permission'
import  transTree from '@/utils/transTree'
import AddPermission from '@/views/Permission/components/add-permission.vue'
export default {
  components: { AddPermission },
  comments: {
    AddPermission
  },
  data() {
    return{
      list: [],
      // params: {
      //   page: 1,
      //   size: 10
      // },
      // total: 0,
      dialogVisible: false,
      // 新增弹框的 type pid
      addType: null,
      addPid: '',
    }
  },
  mounted() {
    this.fetchPermissionList()
  },
  methods: {
    async fetchPermissionList() {
      const res = await getPermissionList()
      this.list =  transTree(res)
      // console.log(transTree(res));
    },
    deletePermission(id){
      // 询问用户
      this.$confirm('此操作将永久删除该权限点, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 调删除接口
          await delPermission(id)
          // 提示用户
          this.$message.success('删除成功')
          // 刷新列表
          this.fetchPermissionList()
        })
    },
    closeDialog() {
      this.dialogVisible = false
    },
    // 添加
    add({type, pid}) {
      this.addType = type
      this.addPid = pid
      // 打开弹窗
      this.dialogVisible = true
    },
    // 编辑
    edit(id) {
      // 打开弹框
      this.dialogVisible = true
      // 调用子组件的getDetail
      this.$refs.dialogForm.getDetail(id)
    }
  }

}
</script>

<style>

</style>